#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
@author: KevinQi
@file: dept.py
@time: 2023/12/27 14:01
@desc:
"""

from backend.workjob.admin.models.permission import Menu, Role, Dept
from backend.workjob.utils.base_requeset import BaseAuthCheckHttpHandler
from backend.workjob.utils.base_response import SuccessResponse, ErrorResponse
from backend.workjob.utils.page_utils import self_pagination


class DeptModelViewSet(BaseAuthCheckHttpHandler):
    """
    部门管理
    """

    def get(self, *args, **kwargs):
        """
        获取部门信息
        """
        if hasattr(self.request, "data"):
            result = Dept.filter_list(self.request.data)
        else:
            result = Dept.all_list()
        data = self_pagination(self.request, data_list=result)
        return self.write(SuccessResponse(data))

    def post(self, *args, **kwargs):
        """
        部门添加
        """
        request_data = self.request.data
        dept_obj = Dept(**request_data)
        dept = Dept.add(dept_obj, self.request)
        return self.write(SuccessResponse(dept))

    def put(self, *args, **kwargs):
        """
        修改部门
        """
        id = self.request.data.get("id")
        if id:
            role = Role.first(id=id)
            if role:
                role.name = self.request.data.get("name")
                role.role_key = self.request.data.get("role_key")
                role.status = self.request.data.get("status")
                role.is_admin = self.request.data.get("is_admin")
                menus = self.request.data.get("menus", [])
                if menus:
                    menus = Menu.filter_in(key="id", filter=menus)
                    role.menu = menus
                    Role.save(role)
                return self.write(SuccessResponse())

    def delete(self, *args, **kwargs):
        """
        删除部门
        """
        id = self.request.data.get("id")
        dept = Dept.first(id=id)
        if dept:
            Dept.delete_soft(id=id)
            return self.write(SuccessResponse(data=[]))
        else:
            return self.write(ErrorResponse(msg="部门不存在不存在"))
